import json
import requests
import os

def create_figma_file(data, access_token):
    """
    根据提取的LVGL数据创建Figma文件
    """
    # Figma API端点
    url = "https://api.figma.com/v1/files"
    
    # 请求头
    headers = {
        "X-Figma-Token": access_token,
        "Content-Type": "application/json"
    }
    
    # 构建Figma文件结构
    figma_structure = build_figma_structure(data)
    
    # 发送请求创建文件
    response = requests.post(url, headers=headers, json=figma_structure)
    
    if response.status_code == 200:
        return response.json()
    else:
        print(f"创建Figma文件失败: {response.status_code}")
        print(response.text)
        return None

def build_figma_structure(data):
    """
    根据LVGL数据构建Figma文件结构
    """
    # 创建文档结构
    document = {
        "name": "LVGL_to_Figma",
        "document": {
            "id": "0:0",
            "name": "Document",
            "type": "DOCUMENT",
            "children": []
        }
    }
    
    # 添加画板
    for screen in data.get("FrontJson", []):
        frame = create_frame(screen, data.get("resolution", {}))
        document["document"]["children"].append(frame)
    
    return document

def create_frame(screen_data, resolution):
    """
    创建Figma Frame
    """
    # 获取分辨率
    width = int(resolution.get("width", 800))
    height = int(resolution.get("height", 480))
    
    frame = {
        "id": f"{screen_data['name']}_frame",
        "name": screen_data["name"],
        "type": "FRAME",
        "x": 0,
        "y": 0,
        "width": width,
        "height": height,
        "children": []
    }
    
    # 添加UI元素
    for element in screen_data.get("list", []):
        if element["type"] == "btn":
            frame["children"].append(create_button(element))
        elif element["type"] == "img":
            frame["children"].append(create_image(element))
        elif element["type"] == "label":
            frame["children"].append(create_label(element))
    
    return frame

def create_button(button_data):
    """
    创建Figma按钮
    """
    return {
        "id": button_data["name"],
        "name": button_data["name"],
        "type": "RECTANGLE",
        "x": button_data["left"],
        "y": button_data["top"],
        "width": button_data["width"],
        "height": button_data["height"],
        "fills": [{
            "type": "SOLID",
            "color": {
                "r": 0.8,
                "g": 0.8,
                "b": 0.8
            }
        }],
        "children": [{
            "id": f"{button_data['name']}_text",
            "name": f"{button_data['name']}_text",
            "type": "TEXT",
            "x": 0,
            "y": 0,
            "width": button_data["width"],
            "height": button_data["height"],
            "characters": button_data["text"],
            "style": {
                "fontFamily": "Roboto",
                "fontSize": 14
            }
        }]
    }

def create_image(image_data):
    """
    创建Figma图片
    """
    return {
        "id": image_data["name"],
        "name": image_data["name"],
        "type": "RECTANGLE",
        "x": image_data["left"],
        "y": image_data["top"],
        "width": image_data["width"],
        "height": image_data["height"],
        "fills": [{
            "type": "IMAGE",
            "imageHash": None  # 需要实际图片文件
        }]
    }

def create_label(label_data):
    """
    创建Figma标签
    """
    return {
        "id": label_data["name"],
        "name": label_data["name"],
        "type": "TEXT",
        "x": label_data["left"],
        "y": label_data["top"],
        "width": label_data["width"],
        "height": label_data["height"],
        "characters": label_data["text"],
        "style": {
            "fontFamily": "Roboto",
            "fontSize": 14
        }
    }

def main():
    # 检查extracted_fields.json文件是否存在
    if not os.path.exists("extracted_fields.json"):
        print("错误: extracted_fields.json文件不存在")
        return
    
    # 读取extracted_fields.json文件
    with open("extracted_fields.json", "r", encoding="utf-8") as f:
        data = json.load(f)
    
    # 检查环境变量中是否有Figma访问令牌
    access_token = os.environ.get("FIGMA_ACCESS_TOKEN")
    if not access_token:
        print("错误: 请设置FIGMA_ACCESS_TOKEN环境变量")
        return
    
    # 创建Figma文件
    result = create_figma_file(data, access_token)
    
    if result:
        print("Figma文件创建成功!")
        print(f"文件URL: {result.get('document', {}).get('url', '')}")
    else:
        print("Figma文件创建失败!")

if __name__ == "__main__":
    main()